package com.mlan.userap.untils;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AACPlayer {
    private static final String TAG = "AACPlayer";
    private final Context context;
    private final String aacUrl; // AAC文件下载地址
    private final String fileName; // 本地文件名
    private MediaPlayer mediaPlayer;
    private final OkHttpClient okHttpClient;
    private final ExecutorService executorService;
    private PlaybackCallback playbackCallback; // 播放回调

    // 回调接口定义
    public interface PlaybackCallback {
        void onPlayFinished();
        void onPlayStart();
        void onError();
    }

    // 构造函数
    public AACPlayer(Context context, String aacUrl, String fileName) {
        this.context = context;
        this.aacUrl = aacUrl;
        this.fileName = fileName;
        this.okHttpClient = new OkHttpClient();
        this.executorService = Executors.newSingleThreadExecutor();
    }

    public String GetFileName(){
        return  fileName;
    }

    // 开始播放逻辑，带回调
    public void start(PlaybackCallback callback) {
        this.playbackCallback = callback; // 设置回调
        File aacFile = getLocalFile();
        if (aacFile.exists()) {
            // 本地文件存在，直接播放
            playAAC(aacFile.getAbsolutePath());
        } else {
            // 文件不存在，下载后再播放
            downloadAndPlay();
        }
    }

    // 从头开始播放
    public void restart() {
        File aacFile = getLocalFile();
        if (!aacFile.exists()) {
            downloadAndPlay(); // 如果文件不存在，触发下载并播放
            return;
        }

        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.seekTo(0);
            } else {
                // 如果已停止，重新初始化并播放
                try {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(aacFile.getAbsolutePath());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    if (playbackCallback != null) {
                        playbackCallback.onError();
                        playbackCallback = null;
                    }
                }
            }
        } else {
            playAAC(aacFile.getAbsolutePath());
        }
    }

    // 获取本地文件路径
    private File getLocalFile() {
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        return new File(directory, fileName);
    }

    // 下载AAC文件并播放
    private void downloadAndPlay() {
        Request request = new Request.Builder()
                .url(aacUrl)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                if (playbackCallback != null) {
                    playbackCallback.onError();
                    playbackCallback = null;
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    return;
                }

                File aacFile = getLocalFile();
                try (FileOutputStream fos = new FileOutputStream(aacFile)) {
                    fos.write(response.body().bytes());
                    fos.flush();
                    // 下载完成，在主线程播放
                    runOnUiThread(() -> playAAC(aacFile.getAbsolutePath()));
                } catch (IOException e) {
                    if (playbackCallback != null) {
                        playbackCallback.onError();
                        playbackCallback = null;
                    }
                }
            }
        });
    }

    // 播放AAC文件
    private void playAAC(String filePath) {
        if (mediaPlayer != null) {
            stop(); // 如果已有播放，停止并释放
        }

        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.start();
            if (playbackCallback != null) {
                playbackCallback.onPlayStart();
            }
            mediaPlayer.setOnCompletionListener(mp -> {
                finished();
            });
        } catch (IOException e) {
            finished();
        }
    }

    // 停止播放并释放资源
    public void stop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    public void finished() {
        stop();
        if (playbackCallback != null) {
            playbackCallback.onPlayFinished();
            playbackCallback = null;
        }
    }
    // 在主线程运行
    private void runOnUiThread(Runnable action) {
        if (context instanceof android.app.Activity) {
            ((android.app.Activity) context).runOnUiThread(action);
        } else {
            executorService.execute(action);
        }
    }

    // 释放资源
    public void release() {
        stop();
        executorService.shutdown();
    }
}